/*注释
 * 	nid=0	普通文本
 * 		cid :
 * 				5 超链接
 * 				6 时间
 *  nid=1	动态数据 （绑定数值的）
 *  	cid:
 *  		7	动态状态值
 *  		11	下发配置值
 *  nid=2	图片
 *  	cid:
 *  		8 svg 格式，可缩放
 *  		9 svg 直线
 *  nid=3	富文本
 *  nid=4	视频
 *  nid=5	图表，折线图，曲线图...管道图
 *   	cid:
 *   		1  折线图
 * 			2  柱形图
 * 			3  仪表盘
 * 			4  液位图
 *  nid=6   地图
 *  nid=7   临时组合框
 *  nid=8   状态
 *  nid=9	控制
 *
 *  nid=10  管道图
 *  		cid = 10
 *
 *  nid=11  设备在离线
 *
 * */
var navPage = ".edit-container";	//画布
// 组态方法类
var cfg = {
	zIndexT: 0 ,			//元素层级
	current_edit_obj: '',	// 当前操作对象
	clone_obj: '',
	init: function(){
		this.elementDrag(".ele-node-info" , ".edit-container");
		this.elementDragCopyInfo(".edit-container");
		// 画布拖动初始化
		$(".edit-container").draggable({
			opacity:1,
			scroll:true,
			scrollSensitivity:0,
			handle:"#canvas_droppable",
			scrollSpeed:0,
			addClasses:false
		});
	},
	elementDrag: function(obj,selector){
		// 拖拽效果
		$(obj).draggable({
			// stop: eleDragCopyStop,
			//handles:" n, e, s, w, ne, se, sw, nw "
			helper:"clone",
			appendTo:"body",
			helper:"clone",
			scroll:false,
			addClass:false,
			revert: false,
			cursor:"move",
			zIndex:1000,
			scope: selector  // 编辑区域
		});
	},
	getRotate: function(matrix){
		//转换成角度
		var aa=Math.round(180*Math.asin(matrix[0])/ Math.PI);
		var bb=Math.round(180*Math.acos(matrix[1])/ Math.PI);
		var cc=Math.round(180*Math.asin(matrix[2])/ Math.PI);
		var dd=Math.round(180*Math.acos(matrix[3])/ Math.PI);
		var deg=0;
		if(aa==bb||-aa==bb){
			deg=dd;
		}else if(-aa+bb==180){
			deg=180+cc;
		}else if(aa+bb==180){
			deg=360-cc||360-dd;
		}
		return deg>=360?0:deg;

	},
	elementDragCopyInfo :function(selector){
		$(selector).droppable({
			activeClass: "ui-state-default",
			hoverClass: "ui-state-hover",
			scroll:false,
			cursor:"move",
			scope: selector ,
			containment:"body",
			drop:function(event, ui)
			{
				//克隆并放置元素
				// var nodeType = ui.helper.attr("nodeType");
				var cl = ui.helper.find(".canvas").clone();//克隆元素
				var nid = cl.attr("nid");//节点类型
				var cid = cl.attr("cid") ;  // 子类型
				//定位
				var x1 = $(selector).offset().top;
				var x2 = ui.offset.top;
				var x  = x2 - x1;//上偏移
				var y1 = $(selector).offset().left;
				var y2 = ui.offset.left;
				var y  = y2 - y1;//左偏移
				var w = "80px";
				var h = "30px";
				//配置元素默认属性
				switch (nid) {
					case "0"://普通文本
						if( cid == 6){
							w="180px;"
						}
						break;
					case "1":// 数据文本
						w = "60px";
						h = "25px";
						break;
					case "2": //图片
						w = "100px";
						h = "100px";
						break;
					case "3"://富文本
						w = "200px";
						h = "200px";
						break;
					case "4"://视频
						w = "300px";
						h = "180px";
						break;
					case "5"://图表
						w = "400px";
						h = "200px";
						break;
					case "6"://地图
						w = "320px";
						h = "160px";
						break;
					case "9":
						w = "70px";
						h = "30px";
						break ;
					case "8":
						w = "40px";
						h = "40px";
						break ;
					case "10":
						w = "300px";
						h = "30px";
						break;
					case "12":
						w = "150px";
						h = "30px";
						break;
					case "13":
						w = "50px";
						h = "30px";
						break;
				}
				// 对于一些自定义大小，需要按照自定义大小进行设置
				var w_val = cl.attr("w") ;
				if( w_val != null && w_val != '' ){
					w = cl.attr("w") ;
					h = cl.attr("h") ;
				}
				//将元素放入编辑区 ,并进行初始化
				var add = cl.appendTo($(this));
				cfg.generateNewNode(add,{"width":w,
					"height":h,
					"top":x,
					"left":y});
				//拖出来后  初始化
				var id = add.attr("id");
				//添加元素后回调
				cfg.current_edit_obj = add;
				switch (nid) {
					case "0":
						if(cid == 6){
							cl.find("span").html(timeStamp2String(new Date())  );
						}
						break ;
					case "1":
						if(cid == 13){
							cl.find("span").html(timeStamp2String(new Date())  );
						}
						break ;
					case "2":
						break ;
					case "3":
						add.removeClass("high-txt");
						break ;
					case "4":	//视频
						var obj_id = "video_"+(cfg.zIndexT-1);
						cl.find(".node_video").attr("id",obj_id);
						break;
					case "5":	//图表
						initTemplateCharts(add);
						break;
					case "6":	//地图
						initTemplateMap(id);
						break;
					case "8":
					case "9":
						initControllerPart(add);
						break ;
					case "10":	//图表
						initSensorPipelineChart(0);
						break ;
					case "11": 	// 设备在离线
						break ;
					case "12":
						var slider_selector = '#'+id +' .slider_container';
						var handle_selector = slider_selector + ' .custom-slider-handle';
						var handle = $(handle_selector);
						$(slider_selector).slider({
							range:"min",
							min:0,
							max:$( this ).attr("max_length"),
							value:0,
							create: function() {
								handle.text( $( this ).slider( "value" ) );
							},
							slide: function( event, ui ) {
								handle.text( ui.value );
							}
						});
						break;
					case '14':
						initSwitchLink(add);
						break;
				}
			}
		})
	},
	generateNewNode:function(obj,style){
		//新节点 添加属性  更新全局变量
		obj.attr("id","node"+ this.zIndexT);	//用于标识唯一
		style['z-index'] = this.zIndexT;
		obj.css(style);
		this.zIndexT++;		//层级+1
	},
	enterEditStatus:function(obj){
		// 进入编辑状态
		this.current_edit_obj = obj;
		//元素是画布
		if(obj.hasClass("edit-container")){
			app.editType = -1;
		} else {
			//素材
			this.activeCommonNode(obj);
			this.updateEditDate(obj);
		}
	},
	activeCommonNode:function(obj){
		//关闭其他的编辑状态
		this.removeNodeEvent($(".activeDrag"));
		//这3个初始化方法要一起用例如没有旋转  拖动会有bug
		obj.draggable({//拖动
			stop: cfg.draggableStopUpdate,
		});
		if(!this.isGroup(obj)){//临时组合框没有旋转和缩放
			obj.resizable({//拉伸
				stop: cfg.resizableStopUpdate,
				handles:" n, e, s, w, ne, se, sw, nw "
			});
			obj.transformable( {
				rotatable:true,
				skewable:false,
				scalable:false,
			});
		}
	    $(obj).addClass("activeDrag");
	},
	draggableStopUpdate:function(e,ui){
		//拖动停止  更新数据
		var u=$(this).getTransform();
	    var o=$(this).tOffset();
	    var edit =  $(".edit-container").offset();	//编辑区
	    $("#node_x").val(o.top-edit.left);
	    $("#node_y").val(o.left-edit.top);
	},
	resizableStopUpdate: function(e,ui){
		//拉伸停止  更新数据,变动大小
	    //如果是图表外层div改变大小 图表也要跟着变
		var cl = cfg.current_edit_obj ;
		var nid = cl.attr("nid") ;
		var cid = cl.attr("cid") ;

		if(nid == 2 && cid == 8){
			// svg图片
			var x = 0 ; //(cl.width()/2- cl.attr("w").substring(0,2) /2 ) / (cl.width()/cl.attr("w").substring(0,2) ) ;
			cl.find("svg").css("transform","scale("+ cl.width()/cl.attr("w").substring(0,2) +","+cl.width()/cl.attr("w").substring(0,2)+") translate("+x+"px,"+x+"px)");
			cl.find("svg").css("position","relative");
			cl.find("svg").css("transform-origin","0 0");
			cl.find("svg").css("margin-left" ,"0");

		}else if(cid == 9){
			cl.find("svg").attr("width",cl.width() ) ;
			cl.find("line").attr("x2" ,cl.width() );
		}
	    changeChartSize(cfg.current_edit_obj);
	},
	removeNodeEvent: function(obj){
		// 清除元素事件
		if(obj.length>0){
			obj.draggable('destroy');
			if(!this.isGroup(obj)){//临时组合框没有旋转和缩放
				obj.resizable('destroy');
				obj.transformable('destroy');
			}
			$(".activeDrag").removeClass("activeDrag");
		}
		$(".textEditActive").removeClass("textEditActive");
	},
	getTranslate:function(node,sty){
		// 获取缩放信息
		var translates=document.defaultView.getComputedStyle(node,null).transform.substring(7);
		var result = translates.match(/\(([^)]*)\)/);
		var matrix=result?result[1].split(','):translates.split(',');
		if(sty=="x" || sty==undefined){
			return matrix.length>6?parseFloat(matrix[12]):parseFloat(matrix[4]);
		}else if(sty=="y"){
			return matrix.length>6?parseFloat(matrix[13]):parseFloat(matrix[5]);
		}else if(sty=="z"){
			return matrix.length>6?parseFloat(matrix[14]):0;
		}else if(sty=="rotate"){
			return matrix.length>6? this.getRotate([parseFloat(matrix[0]),parseFloat(matrix[1]),parseFloat(matrix[4]),parseFloat(matrix[5])]):this.getRotate(matrix);
		}
	},
	isGroup($obj){	//是否是组合
		if($obj.hasClass("tempGroup")){
			return true;
		}
		return false;
	},
	inGroup($obj){	//是否在组合内
		if($obj.parent().parent().hasClass("tempGroup")){
			return true;
		}
		return false;
	},
	updateEditDate: function(obj){   // 编辑元素时，信息回显，更新元素的属性到操作栏上，判断素材类型
		var nid = obj.attr("nid");	 // 元素种类
		app.cid =  obj.attr("cid");	 // 子类型
		var id = obj.attr("id");
		app.nid = nid ;
		// 类型
		app.editType = nid ;
		switch (nid) {
			case '0'://普通文本
				var text = obj.find(".canvas_text").text();
				app.edit_text = text.trim() ;
				app.jty = parseInt(gdv( obj.attr("jty"),1 ) );
				app.jurl = obj.attr("jurl");
				app.visual_select_code = obj.attr("code");
				app.visual_select_width = obj.attr("width");
				app.visual_select_height = obj.attr("height");
				break;
			case '3'://富文本
				cfg.initRichText(obj);
				$(".text_toolbar_item").hide();
				$(".text_toolbar_item[tag='"+id+"']").css("display","flex");
				break;
			case '5':
				app.chartMax = obj.attr("max") ;
				break ;
			case '8':
			case '9':
				app.dattribute = gdv( eval('('+ obj.attr('cmd') +')') , [] );
				break ;
			case '10':
				//获取流动速度
				var myChart = getEchartObj();
				option = myChart.getOption();
				var speed = option.series[0].effect.constantSpeed;
				app.rotate_speed = speed;
				$("#rotate_speed").slider({
					value:speed
				});
				break ;
			case '12':
				app.slider_length= obj.find(".slider_container").attr("max_length");
				break ;
			case '14':
				var text = obj.find(".canvas_text").text();
				app.edit_text = text.trim() ;
				app.linkAttribute = gdv( eval('('+ obj.attr('cmd') +')') , [] );
				break ;
			default:

				break;
		}
		//数据
		var node_id = gdv(obj.attr("node_id"),"");
		var isModbus = gdv(obj.attr("isModbus"),"");
 		var green_house_id = gdv(obj.attr("green_house_id"),"");
 		var sensor_id_father = gdv(obj.attr("sensor_id_father"),"");
 		var sensor_id = gdv(obj.attr("sensor_id"),"");
		var device_slave_id = gdv(obj.attr("device_slave_id"),"");
		var cid = gdv(obj.attr("cid"),"");
		var video_id = gdv(obj.attr("video_id"),"") ;
		var textTitle = gdv(obj.attr("textTitle"),"");
		var video_way = gdv(obj.attr("video_way"),'1');
		var video_type = gdv(obj.attr("video_type"),'1');
		var video_url = gdv(obj.attr("video_url"),"");
		if(video_way != ''){
			app.video_way = video_way;
		}else{
			app.video_way = '';
		}
		if(video_type != ''){
			app.video_type = video_type;
		}else{
			app.video_type = '';
		}
		if(video_url != ''){
			app.video_url = video_url;
		}else{
			app.video_url = '';
		}
		if(textTitle != ''){
			app.textTitle = textTitle;
		}else{
			app.textTitle = '';
		}
		if(node_id != ''){
			app.node_id = node_id;
		}else{
			app.node_id = '';
		}
		if(isModbus != ''){
			app.isModbus = isModbus;
		}else{
			app.isModbus = '';
		}
		if(device_slave_id != ''){
			app.device_slave_id = device_slave_id;
		}else{
			app.device_slave_id = '';
		}
		if( sensor_id != '' ){
			app.sensor_id =sensor_id ;
		}else{
			app.sensor_id = '' ;
		}
		if( sensor_id_father != '' ){
			app.sensor_id_father =sensor_id_father ;
			if (sensor_id_father!==sensor_id){
				app.child_sensor=true
			}else{
				app.child_sensor=false
			}

		}else{
			app.sensor_id_father = '' ;
		}
		if( green_house_id != '' ){
			app.green_house_id =parseInt(green_house_id );
		}else{
			app.green_house_id = '' ;
		}
		app.cid = cid;
		if(video_id != ''){
			app.video_id = video_id;
		}else{
			app.video_id = '' ;
		}

		if( nid == '1' ||  nid == '5' || nid == '6' || nid == '8' || nid == '9' || nid == '10' ){
			if( nid  != '6' ){
				app.initSensorList( );
				if (sensor_id_father!==sensor_id){
					app.initChildSensorList(sensor_id_father)
				}
			}
		}

		if(( nid == '1' ||  nid == '5' || nid == '6' || nid == '8' || nid == '9' ) && app.model=='0'){
			app.initGreenHouseIdList();
			app.initNodeList();
		}

		// 文本样式初始化
		app.fontSize = $(cfg.current_edit_obj).css("font-size");
		app.lineHeight = '' ;
		app.fontFamily = '' ;
		app.textalign = $(cfg.current_edit_obj).css("text-align")=='start'?'':$(cfg.current_edit_obj).css("text-align") ;

		//css
		var top = $(cfg.current_edit_obj).css("top");
		var left = $(cfg.current_edit_obj).css("left");
		var width = $(cfg.current_edit_obj).css("width");
		var height = $(cfg.current_edit_obj).css("height");
		var bcolor = $(cfg.current_edit_obj).css("background-color");
		var transform = this.getTranslate($(cfg.current_edit_obj)[0],"rotate");
		//旋转角度
		if(transform !=null && transform !='none'){
			app.rotate = transform ;
		} else {
			app.rotate = 0 ;
		}
		app.rotateChange();
		// x,y,w,h
		app.canswidth= parseFloat(width);
		app.cansheight = parseFloat(height) ;
		app.canvensx = parseFloat(left) ;
		app.canvensy = parseFloat(top) ;

		if(bcolor != 'rgba(0, 0, 0, 0)'){
			$("#backcolor").spectrum("set", bcolor);
		}else{
			$("#backcolor").spectrum("set", "transparent");
		}
	},
	initRichText :function(obj){
		var id = obj.attr("id");
		var nid = obj.attr("nid");
		//富文本 且 没有经过初始化
		if(nid=="3" && $('.text_toolbar_item[tag="'+id+'"]').length==0){
			$(".text_toolbar").append("<div class='text_toolbar_item' tag='"+id+"'></div>");
			var E = window.wangEditor;
			// 两个参数也可以传入 elem 对象，class 选择器
			var editor = new E('.text_toolbar_item[tag="'+id+'"]', "#"+id) ;
			// 配置菜单
			editor.customConfig.menus = [
				'head',
				'bold',
				'italic',
				'underline',
				'strikeThrough',
				'link',
				'foreColor',
				'backColor',
				'justify',
				 'list',
				'undo',
				'redo'
			];
			if( $("#"+id +" .w-e-text").length > 0  ){
				var content = $("#"+id +" .w-e-text").html() ;
				$("#"+id).empty();
				$("#"+id).append(content) ;
			}
			editor.create();
			editor.$textElem.attr('contenteditable', false);
			//对z-index特殊处理
			var $menu_arr = $('.text_toolbar_item[tag="'+id+'"]').children(".w-e-menu");
			$menu_arr.eq(0).css("z-index","100007");
			$menu_arr.eq(2).css("z-index","100006");
			$menu_arr.eq(3).css("z-index","100005");
			$menu_arr.eq(7).css("z-index","100004");
			$menu_arr.eq(8).css("z-index","100003");
			$menu_arr.eq(10).css("z-index","100002");
			$menu_arr.eq(11).css("z-index","100001");
		}
	},
	hideDraggableEvent: function(obj){
		if(obj.length>0){
			obj.draggable('disable');
		}
	},
	//菜单拖拽事件 给新元素添加事件
	activeMenuNode(obj){
		obj.draggable({//拖动
			//stop: initCharts,
			//handles:" n, e, s, w, ne, se, sw, nw "
			helper:"clone",//克隆
			appendTo:"body",
			helper:"clone",
			scroll:false,
			addClass:false,
			revert: false,
			cursor:"move",
			zIndex:9999,
			scope:".edit-container",
		});

	},
	//删除组合
	groupDel(){
		if($(".edit-container").find(".tempGroup").length != 0){
			var GroupTop  = $(".tempGroup").css("top").replace(/[a-z]/g,"");
			var GroupLeft = $(".tempGroup").css("left").replace(/[a-z]/g,"");
			$(".tempGroup > .canvas-con > .resiz_canvas").unwrap().unwrap();
			$(".Equal").removeClass("Equal");
			$(navPage+"> .resiz_canvas").each(function()
			{
				var thisTop   = $(this).css("top").replace(/[a-z]/g,"");
				var thisLeft  = $(this).css("left").replace(/[a-z]/g,"");
				var top       = Number(thisTop) + Number(GroupTop);
				var left      = Number(thisLeft) + Number(GroupLeft);
				$(this).css({"top":top,"left":left});

				$(this).removeClass("resiz_canvas");
			});
		}
	}
}

/* 颜色选择器 */
function initColorSelect(selectot, move,show){
	$(selectot).spectrum({
	    allowEmpty:true,
	    color:"transparent",
	    showInput: true,
	    containerClassName: "full-spectrum",
	    showInitial: true,
	    showPalette: true,
	    showSelectionPalette: true,
	    showAlpha: true,
	    maxPaletteSize: 10,
	    preferredFormat: "hex",
		cancelText: "关闭",
		chooseText: "确定",
	    palette: [
	            ["#000","#444","#666","#999","#ccc","#eee","#f3f3f3","#fff"],
	            ["#f00","#f90","#ff0","#0f0","#0ff","#00f","#90f","#f0f"],
	            ["#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#cfe2f3","#d9d2e9","#ead1dc"],
	            ["#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#9fc5e8","#b4a7d6","#d5a6bd"],
	            ["#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6fa8dc","#8e7cc3","#c27ba0"],
	            ["#c00","#e69138","#f1c232","#6aa84f","#45818e","#3d85c6","#674ea7","#a64d79"],
	            ["#900","#b45f06","#bf9000","#38761d","#134f5c","#0b5394","#351c75","#741b47"],
	            ["#600","#783f04","#7f6000","#274e13","#0c343d","#073763","#20124d","#4c1130"]
	    ],
	    move: function (color) {
			if( move !=null){
				move(color);
			}
	    },
	    show: function (color) {
			if(show !=null){
				show(color);
			}
	    },
	    beforeShow: function () {

	    },
	});
};

function initImgUpload(id){
	//上传模板
	UploadInit( baseurl + 'yesiot/fileInfo/save' , {category:"img"} ,function(file,data){
		if(data.resp_code===0){
			var url = data.datas.url;
			saveImg(url);
			setTimeout(function(){
				cfg.activeMenuNode($("#upload_img_"+ app.uploadImgCount));
			}, 1000);
		}
	}, id ,id,"110px", "35px") ;
}

/**
 * 上传背景图
 * @param url
 * @returns
 */
function initBgImgUpload(id){
	//上传模板
	UploadInit( baseurl + 'yesiot/fileInfo/save' , {category:"img"} ,function(file,data){
		if(data.resp_code===0){
			var url = data.datas.url;
			// 上传成功
//			$(".edit-container").attr("bgurl",url) ;
//			$(".edit-container").parent().css("background","url("+ url +")  no-repeat ") ;
//			$(".edit-container").parent().css("background-position","center top") ;
			$(".edit-container").css("background-image","url("+ url +")") ;
			$(".edit-container").css("background-position","0% 0%") ;
			$(".edit-container").css("background-size","100% 100%") ;
			$(".edit-container").css("background-repeat","initial") ;
			$(".edit-container").css("background-attachment","initial") ;
			$(".edit-container").css("background-origin","initial") ;
		}
	}, id ,id,"110px", "35px") ;
}
function initImgLoginUpload(id){
	//上传模板
	UploadInit( baseurl + 'yesiot/fileInfo/save' , {category:"img"} ,function(file,data){
		if(data.resp_code===0){
			var url = data.datas.url;
			// 上传成功
			app.loginLogo=url;
		}
	}, id ,id,"110px", "35px") ;
}


function saveImg(url){
	var data = {
		name:'上传图片',
		disImg:url,
		moudleType:'1',
		visualMoudleLibraryId:app.activeNameImgKun1
	}
	commonAjax("POST",baseurl+"yesiot/moudle/visual/save", data,function(e){
		if(e.resp_code === 0){
			app.uploadImgCount = e.datas.id;
			app.addUploadImg(url,e.datas.id,e.datas.visualMoudleLibraryId);
			app.$message({
		          message: '成功',
		          type:'success'
		    });
			/*app.initUploadImgList();*/
		}else{
			app.$message.error(e.resp_msg);
		}
	});
}
/**
 * @Func 文件上傳功能，目前只支持單個
 * @param imgUrl domain
 * @param user_id 用戶id
 * @param func 成功之後的回調
 * @Param id 文件选择id
 */
function UploadInit(imgFindUrl, userInfo ,func,id,domId,thumbnailWidth, thumbnailHeight,accept,acceptconfig){
    var $ = jQuery,
        state = 'pending',
        uploader;
	// 增加类型修改，可以传入类型
	if(accept == undefined){
    	acceptconfig =  "" ;
    }else{
    	acceptconfig = getVal( acceptconfig, {   // 默认值兼容之前
	          title: 'Images',
	          extensions: 'gif,jpg,jpeg,bmp,png,pdf',
	          mimeTypes: 'image/jpg,image/jpeg,image/png'
	        });
    }

    uploader = WebUploader.create({
    	// 自动上传
    	auto: true,
        // 不压缩image
        resize: false,
        //不压缩图片
        compress:false,
        // swf文件路径
        swf: '../lib/webUploader/Uploader.swf',
        // 文件接收服务端。
        server: imgFindUrl,
        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: '#'+id ,
        duplicate: true ,
        fileSingleSizeLimit: 5*1024*1024,
      // 只允许选择文件，可选。
        accept:acceptconfig
    });
	uploader.on("uploadBeforeSend",function (object,data,headers) {
		let parse = JSON.parse(localStorage.getItem("layuiAdmin"));
		/*
		$.extend(headers, {
			"X-Authorization": "Bearer " + (JSON.parse(parse.token)).token
		});*/
	})
    uploader.on("error",function (type){
        if (type=="Q_TYPE_DENIED"){
        	if(typeof(layer)!="undefined"){
        		showTip("请上传正确的文件格式");
        	}else{
        		alert("请上传正确的文件格式");
        	}
        }else if(type=="F_EXCEED_SIZE"){
        	if(typeof(layer)!="undefined"){
        		showTip("文件大小不能超过5M");
        	}else{
        		alert("文件大小不能超过5M");
        	}
        }
    });
    // 当有文件添加进来的时候
    uploader.on('fileQueued', function(file) {
    	$("#"+domId).css("width","0%");
    	$("#"+domId).attr("ids","");
    	$("#"+domId).css("display","inherit");
    	uploader.options.formData= gdv(userInfo , {}) ;
    	uploader.makeThumb( file, function( error, src ) {
           $("#back_"+domId).css("background","url("+src+")");

        }, thumbnailWidth, thumbnailHeight );
    });
    // 文件上传过程中创建进度条实时显示。
    uploader.on('uploadProgress', function(file, percentage) {
    	$("#all_"+domId).text(parseInt(percentage*100)+"%");
    	$("#"+domId).css("width",parseInt(100-percentage*100)+"%");
    });
    uploader.on('uploadSuccess', func);
    uploader.on('uploadError', function(file) {
    	console.log("文件上传出错");
    });
    uploader.on('uploadComplete', function(file) {
    });
    uploader.on('all', function(type) {
    });
	uploader.refresh();
};
//------------------------------------------------------------------------------------------
// 组件模块化(初始化图片)
function initControllerPart(obj){
	var cmd = gdv( eval('('+ obj.attr('cmd') +')') , [] );
	var cmdValue = gdv( obj.attr('val') , 0 ) ;
	for( var i=0; i < cmd.length ; i++ ){
		if( cmdValue >= cmd[i].min && ( (cmd[i].min == cmd[i].max && cmdValue == cmd[i].max ) || cmdValue < cmd[i].max )){
			obj.find("img").attr("src" , cmd[i].src );
			obj.find(".img-title").text(cmd[i].title);
			break ;
		}
	}
}

function initSwitchLink(obj){
	var cmd = gdv( eval('('+ obj.attr('cmd') +')') , [] );
	var cmdValue = obj.attr('jval');
	if(!isNaN(Number(cmdValue))) {
		cmdValue = gdv( obj.attr('jval') , 0 ) ;
	}
	for( var i=0; i < cmd.length ; i++ ){
		if(cmd[i].is_num != false) {
			if( cmdValue >= cmd[i].min && ( (cmd[i].min == cmd[i].max && cmdValue == cmd[i].max ) || cmdValue < cmd[i].max )){
				obj.attr("href" , cmd[i].jurl );
				break ;
			}
		} else {
			if( cmdValue == cmd[i].val ){
				obj.attr("href" , cmd[i].jurl );
				break ;
			}
		}
	}
}

//初始模板图表
function initTemplateCharts(obj){
	//如果是液位图则不使用默认折线图
	var cid = obj.attr("cid");
	cfg.current_edit_obj = obj;

	// 液位图
	if(cid==4){
		initSensorLiquidChart();
		return;
	}
	//默认折线图
	var chart = obj.find(".chartStyle");
	chart.attr("id",obj.attr("id")+"_chart")
//	var myChart = echarts.init(chart[0], null, {renderer: 'svg'});   // svg方式
	var myChart = echarts.init(chart[0]);
	option = {
	    xAxis: {
	        type: 'category',
	        data: ['2020/06/01', '2020/06/02','2020/06/03','2020/06/04','2020/06/05']
	    },
	    tooltip: {
	        trigger: 'axis'
	    },
	    grid: {
	       left: '10%',
	       right: '2%',
	       bottom: '10%',
	       top: '15%'
	    },
	    yAxis: {
	        type: 'value'
	    },
	    series: [{
	        data: [820, 932, 901, 934, 1290],
	        type: 'line'
	    }]
	};
	myChart.setOption(option,true);
	chart.attr("option",JSON.stringify(option));
	app.chartMap[obj.attr("id")] = myChart;
}

//初始化传感器折线图
function initSensorLineChart(){
	var current_edit_obj = cfg.current_edit_obj;
	var chart = getEchartObj();
	var x_data = ['2020/06/01', '2020/06/02','2020/06/03','2020/06/04','2020/06/05'];
	var y_data =  [820, 932, 901, 934, 1290];
	option = {
    		tooltip: {
		        trigger: 'axis'
		    },
    	    xAxis: {
    	        type: 'category',
    	        data: x_data
    	    },
    	    yAxis: {
    	        type: 'value'
    	    },
    	    grid: {
		       left: '10%',
		       right: '2%',
		       bottom: '10%',
		       top: '15%'
		    },
    	    series: [{
    	        data: y_data,
    	        type: 'line'
    	    }]
    	};
    setChartOption(chart,option);

}
//初始化传感器柱形图
function initSensorBarChart(){
	var current_edit_obj = cfg.current_edit_obj;
	var chart = getEchartObj();
	var x_data = ['2020/06/01', '2020/06/02','2020/06/03','2020/06/04','2020/06/05'];
	var y_data =  [820, 932, 901, 934, 1290];
	option = {
    		tooltip: {
		        trigger: 'axis'
		    },
    	    xAxis: {
    	        type: 'category',
    	        boundaryGap: true ,
    	        data:x_data
    	    },
    	    yAxis: {
    	        type: 'value'
    	    },
    	    grid: {
    		       left: '10%',
    		       right: '2%',
    		       bottom: '10%',
    		       top: '15%'
    		    },
    	    series: [{
    	        data: y_data,
    	        type: 'bar',
    	        barWidth: 30
    	    }]
    	};
    setChartOption(chart,option);
}
//初始化传感器仪表盘
function initSensorDashChart(){
	var current_edit_obj = cfg.current_edit_obj;
	var chart = getEchartObj();
	option = {
	    series:[{
	        	name: "name",
	            type: "gauge",
	            radius : "98%",
	            axisLine : {
	                lineStyle : {
	                     width : 20,
						color: [[0.2, '#c23531'], [0.8, '#63869e'], [1,'#91c7ae']]
					}
                },
                splitLine : {
                    length : 20
                },
	            detail: {formatter: '{value}'},
	            data: [{ value: 20, name: '传感器1'}]
	        }
	    ]
	} ;
	setChartOption(chart,option) ;
}
//初始化传感器液位图
function initSensorLiquidChart(){
	var current_edit_obj = cfg.current_edit_obj;
	var chart = getEchartObj();
	var xn  = 500;
	var max = 1000;
	var bai = 0.5;
	var siz = 20;
	let option = {
	    series: [{
	        type:'liquidFill',
			name:'设备',
	        data:[{
				name:'传感器',
				value:bai
			}],
	        direction:'right',//波浪方向或者静止
	        shape:'container',
	        //color:['rgba(43, 110, 204, 0.7)'],//水球颜色
	        center:['50%', '50%'], //水球位置
			amplitude:8,//波浪幅度
	        outline://外边
	        {
	        	show:false
	        },
	        label:{
				formatter:function(param){
					return param.seriesName + '\n'
						+ param.name + '\n'
						+ max +'单位/'+ xn +'单位('+param.value*100+'%)';
				},
				fontSize:siz,
			},
	        backgroundStyle://内图背景色边
	        {
	            color:'rgba(0, 0, 0, 0)',
	        },
	        itemStyle: {
		        opacity: 0.95,
		        shadowBlur: 0,
		        shadowColor: 'rgba(0, 0, 0, 0)'
		    },
	    }]
	};
	//使用刚指定的配置项和数据显示图表。
	setChartOption(chart,option) ;
	/*setInterval(function()
	{
		xn  = (Math.random().toFixed(1))*1000;
		bai = xn/max;
		chart.setOption(
		{
			series:[
			{
				data:[{name:'传感器',value:bai}]
			}]
		});
    },2000)*/
}

//管道图
function initSensorPipelineChart(type){
	// 基于准备好的dom，初始化echarts实例
	var current_edit_obj = cfg.current_edit_obj;
	var myChart = getEchartObj();
	if(type==null || type=='0'){		//初始化
		app.speed_dir = 'r';		//默认向右
		//重新计算流动所需要的数据
		var result = calcPipelineParam();
		var th = result.th;
		var tz = result.tz;
		var tw = result.tw;
		var fd = result.fd;
		var xw = result.xw;
		var co = result.co;
		option = {
				grid:{
					top:0,
					left:0,
					right:0,
					bottom:'50%'
				},
				xAxis:{
					splitLine: {
						show: false
					},
					axisLine: {
						show: false
					},
					axisTick: {
						show: false
					},
					axisLabel: {
						show: false
					},
					max:xw,
					min: 0
				},
				yAxis:{
					silent: true,
					splitLine: {
						show: false
					},
					axisLine: {
						show: false
					},
					axisTick: {
						show: false
					},
					axisLabel: {
						show: false
					},
					max:xw,
					min: 0
				},
				series:[{
					coordinateSystem: 'cartesian2d',
					type: 'lines',
					polyline: true,
					zlevel: 1,
					effect:
					{
						show: true,
						constantSpeed:60,
						delay:0,
						symbolSize: [tz,tw],
						symbol: '../image/gd2.png',
						trailLength:0.5,
						loop: true,
					},
					lineStyle:{
						normal: {
							width:th,
							color:{
								type: 'linear',
								x: 0,
								y: 0,
								x2: 0,
								y2: 1,
								colorStops: [{
									offset: 0,
									color: '#6d7b92' // 0% 处的颜色
								}, {
									offset: 0.5,
									color: '#f4f8fa' // 100% 处的颜色
								}, {
									offset: 1,
									color: '#6d7b92' // 100% 处的颜色
								}],
								globalCoord: false // 缺省为 false
							},
							opacity: 1,
							curveness: 0,
							type: 'solid',
						}
					},
					data:co
				}]
		};
		//使用刚指定的配置项和数据显示图表。
		myChart.setOption(option);
		setChartOption(myChart,option) ;

	} else if(type=="1"){		//重置图表大小和液体个数
		var w  = current_edit_obj.width();
		var h  = current_edit_obj.height();
		if(h >= 1 && w >= 1){
			//重新计算流动所需要的数据
			var result = calcPipelineParam();
			var th = result.th;
			var tz = result.tz;
			var tw = result.tw;
			var fd = result.fd;
			var xw = result.xw;;
			var co = result.co;
			var reset_option = {
					xAxis:{
				        max:xw,
				        min: 0
				    },
				    yAxis:{
				        max:xw,
				        min: 0
				    },
					series:[{
						effect:{
				            symbolSize: [tz,tw]
				        },
						lineStyle:{
				            normal:{
				                width: th
				            }
				        },
				        data:co
					}]
				};
			myChart.setOption(reset_option,false);
			myChart.resize();

			option = mergePipilineChartOpetion(reset_option);
			option.series.data = co;

			option = myChart.getOption();
			saveChartOption(option);
		}
	}
}

//合并管道图参数
function mergePipilineChartOpetion(new_option){
	var current_edit_obj = cfg.current_edit_obj;
	option = JSON.parse(current_edit_obj.children(".chartStyle").attr("option"));
	$.extend(option, new_option);
	option.coordinateSystem = 'cartesian2d';
	option.type =  'lines';
	option.polyline =  true;
	option.zlevel =  1;
	return option;
}
//修改管道图速度和方向
function resetPipelineChartSpeedAndDir(speed,dir){
	if(speed==null){
		speed = app.rotate_speed
	}
	if(speed == 0){
		speed = 0 ;
	}
	if(dir==null){
		dir = app.speed_dir
	}
	var current_edit_obj = cfg.current_edit_obj;
	var myChart = getEchartObj();
	//重新计算流动所需要的数据
	var result = calcPipelineParam(dir);
	var th = result.th;
	var tz = result.tz;
	var tw = result.tw;
	var fd = result.fd;
	var xw = result.xw;;
	var co = result.co;
	//
	var reset_option = {
		series:[{
			effect:{
				constantSpeed:speed
			},
			data:co
		}]
	};
	myChart.setOption(reset_option,false);

	option = mergePipilineChartOpetion(reset_option);
	option.series.data = co;

	option = myChart.getOption();
	saveChartOption(option);
}

/**
 * 计算管道内液体流动的方向
 * @param dir
 * @returns
 */
function calcPipelineParam(dir){
	var current_edit_obj = cfg.current_edit_obj;
	var speed_dir = app.speed_dir;//流动方向
	if(dir==null){
		dir = app.speed_dir ;
	}
	var w  = parseFloat(current_edit_obj[0].style.width);
	var h  = parseFloat(current_edit_obj[0].style.height);
	var th = parseInt(h*0.8);
	var tz = parseInt(h*0.6);
	var tw = parseInt(tz * 3.5);
	var fd = parseInt(w/(tw*1.4));
	var xw;
	var co = [];
	if(fd == 0){
		tw = parseInt(w*0.8);
		tz = parseInt(tw/3.5);
		if(dir=='r'){
			co.push({coords:[[0, 0],[w, 0]]});
		} else {
			co.push({coords:[[w, 0],[0, 0]]});
		}
		xw = w;
	}else{
		var num = parseInt(w/fd);
		xw = num*fd;
		for(var a=0;a<fd;a++)
		{
			if(dir=='r'){
				co.push({coords:[[(num*a)-1, 0],[num*(a+1), 0]]});
			} else {
				co.push({coords:[[num*(a+1), 0],[(num*a)-1, 0]]});
			}
		}
	}
	var result = {
		tz:tz,
		tw:tw,
		xw:xw,
		co:co,
		th:th,
		fd:fd
	};
	return result;
}

function setChartOption(chart,option){
	chart.setOption(option,true);
    saveChartOption(option);
}
function saveChartOption(option){
    cfg.current_edit_obj.children(".chartStyle").attr("option",JSON.stringify(option));
}
//获取echarts对象
function getEchartObj(){
	var current_edit_obj = cfg.current_edit_obj;
	var chart = app.chartMap[current_edit_obj.attr("id")];
	if(chart == null){
		var $chartHtml = current_edit_obj.children(".chartStyle");
		$chartHtml.html("");
		chart = echarts.init($chartHtml[0]);
//		chart = echarts.init($chartHtml[0], null, {renderer: 'svg'});
		app.chartMap[current_edit_obj.attr("id")] = chart;
	}
	return chart
}
//初始化模板地图
function initTemplateMap(id){
	// 这边退出
	return ;
}
/**
 * 选择框变动的时候，请求数据
 * @param id
 * @returns
 */
function resetNodeData(id,type){
	var current_edit_obj = cfg.current_edit_obj;
	var nid = current_edit_obj.attr("nid");
	var cid = current_edit_obj.attr("cid");
	var node_id = current_edit_obj.attr("id");
	if(nid=="1" ){
		//	动态数据类
	} else if(nid=="4"){	//视频
	} else if(nid=="5"){
		if(cid == "1"){			//折线图
			initSensorLineChart();
		} else if(cid == "2"){	//柱形图
			initSensorBarChart();
		} else if(cid == "3"){	//仪表盘
			initSensorDashChart();
		} else if(cid == "4"){	//液位图
			initSensorLiquidChart();
		}
	} else if(nid=="6"){		//地图
		return ;
	}
}

function initVideo(id){
	var player = new EZUIPlayer(id);
    player.on('error', function(){
	   console.log('error');
    });
    player.on('play', function(){
	   console.log('play');
    });
    player.on('pause', function(){
	   console.log('pause');
    });
}

//如果是图表外层div改变大小  图表也要跟着变
function changeChartSize(obj){
	var nid = obj.attr("nid");
	//var current_edit_obj = cfg.current_edit_obj;
	if(nid == "5"){
		var myChart = getEchartObj();
		myChart.resize();
	} else if(nid == "10"){
		// 重新初始化 管道图
		initSensorPipelineChart(1);
	}
}
//第一次进入的时候重新初始化chart对象  取标签中的option属性重新初始化
function reinitChartObj(){
	var chartMap = app.chartMap;
	$(".chartStyle").each(function(){
		var id = $(this).parent().attr("id");
		if(id!=null){
			var json = $(this).attr("option");
			var myChart = echarts.init($(this)[0]);
			myChart.setOption(JSON.parse(json),true);
			app.chartMap[id] = myChart;
		}
	})
}

function reInitSliderObj(){
	$(".slider_container.ui-slider").each(function(){
		var id = $(this).parent().attr("id");
		var max_length = $(this).attr("max_length");
		$(this).siblings().remove();
		var slider_selector = '#'+id +' .slider_container';
		var handle_selector = slider_selector + ' .custom-slider-handle';
		var handle = $(handle_selector);
		$(slider_selector).slider({
			range:"min",
			min:0,
			max:$( this ).attr("max_length"),
			value:0,
			create: function() {
				handle.text( $( this ).slider( "value" ) );
			},
			slide: function( event, ui ) {
				handle.text( ui.value );
			}
		});
		var ranges = $(slider_selector).find(".ui-slider-range");
		if(ranges.length > 1) {
			ranges.each(function (index,item) {
				if(index < ranges.length-1) {
					item.remove();
				}
			})
		}
	})
}


// 形成xy线
//function initLine(){
//	debugger
//	var ox = document.createElement('div');
//	var oy = document.createElement('div');
//	ox.style.width = '100%';
//	ox.style.height = '1px';
//	  ox.style.backgroundColor = '#ddd';
//	  ox.style.position = 'fixed';
//	  ox.style.left = 0;
//	  $(navPage).append(ox);
//	  oy.style.height = '100%';
//	  oy.style.width = '1px';
//	  oy.style.backgroundColor = '#ddd';
//	  oy.style.position = 'fixed';
//	  oy.style.top = 0;
//	  $(navPage).append(oy);
//	  $(navPage).mousemove(function(e){
//		  var e = e || event;
//		  var x = e.pageX;
//		  var y = e.pageY;
//		  ox.style.top = y + 'px';
//		  oy.style.left = x + 'px';
//	}) ;
//}


/**
 * 获取默认值
 * @param value
 * @param default_val
 * @returns
 */
function gdv(value,default_val){
	if(value!=undefined && value+''!=""  && value!='undefined'){
		return value ;
	}else{
		if(default_val != undefined)
			return default_val ;
		return "";
	}
};

/**
 * 返回值判断
 */
var isOk= isOK ;
function isOK(e){
	if(e.status == 2 ){
		return true ;
	}else{
		return false ;
	}
}

/**
 * ajax请求
 * @param url
 * @param sucessCallBack
 * @param errorCallBack
 * @returns
 */
function getToken(){
	//检查是否登录
	let token = localStorage.getItem('TOKEN')
	if(!token) {
		top.location.replace('login.html');
	}
	return 'Bearer ' + token
	// let cookieStr=document.cookie
	// var arrcookie = cookieStr.split(";");
	// for ( var i = 0; i < arrcookie.length; i++) {
	// 	var arr = arrcookie[i].split("=");
	// 	if (arr[0] === 'Authorization'){
	// 		let s = arr[1].replace("%20"," ");
	// 		if (s!=null && s!==undefined && s!==''){
	// 			return s
	// 		}else{
	// 			top.location.replace('login.html');
	// 		}
	// 	}
	// }
}
function getAjax(url, sucessCallBack, errorCallBack) {
	if(typeof(ucode)=="undefined"){
		ucode='';
	}
	let token=getToken();
	$.ajax({
		type : "GET",
		url : url,
		contentType : "application/json",
		dataType : "json",
		async : true,
		headers : {
			'Authorization' :token
		},
		success : function(data){
			sucessCallBack(data);
		},
		error : errorCallBack
	})
};

var doAjaxPostData = commonAjax;
function commonAjax(method,url, data,sucessCallBack, errorCallBack) {
	var config = {
		type : method ,
		url : url,
		contentType : "application/json",
		dataType : "json",
		async : true,
		success : function(data){
			if(data.status == 20000){
				return;
			}else{
				sucessCallBack(data);
			}
		},
		error : errorCallBack
	};
	let token=getToken();
	if(token){
		config.headers={  'Authorization' :token  };
	}
	if(method.toUpperCase() != 'GET' &&  method.toUpperCase() != 'DELETE'  ){
		config.data = JSON.stringify(data);
	}
	$.ajax(config)
};
function commonAjaxFalse(method,url, data,sucessCallBack, errorCallBack) {
	var config = {
		type : method ,
		url : url,
		async : false,
		contentType : "application/json",
		dataType : "json",
		success : function(data,status,xhr){
			if (xhr.status == 401) {
				layer.msg('登录过期', {icon: 2, time: 3000}, function () {
					top.location.replace('login.html');
				}, 1000);
				return;
			}
			sucessCallBack(data,status,xhr);
		},
		error : errorCallBack
	};
	let token=getToken();
	if(token){
		config.headers={  'Authorization' :token  };
	}
	if(method.toUpperCase() != 'GET' &&  method.toUpperCase() != 'DELETE'  ){
		config.data = JSON.stringify(data);
	}
	$.ajax(config)
}
function tip(content,time,func){
	if(content == undefined){
		content = "error";
	}
	try{
		if( time==null || time == '' )
			time = 1200 ;
		if( func==null )
			layer.msg(content,{time:time});
		else{
			layer.msg(content,{time:time},function(){
				func();
			});
		}
	}catch(e){
	}
};
function toCode  (str) {  //加密字符串
	//定义密钥，36个字母和数字
	var key = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var st = key.length;  //获取密钥的长度
	var a = key.split("");  //把密钥字符串转换为字符数组
	var s = "",b, b1, b2, b3;  //定义临时变量
	for (var i = 0; i <str.length; i ++) {  //遍历字符串
		b = str.charCodeAt(i);  //逐个提取每个字符，并获取Unicode编码值
		b1 = b % st;  //求Unicode编码值得余数
		b = (b - b1) / st;  //求最大倍数
		b2 = b % st;  //求最大倍数的于是
		b = (b - b2) / st;  //求最大倍数
		b3 = b % st;  //求最大倍数的余数
		s += a[b3] + a[b2] + a[b1];  //根据余数值映射到密钥中对应下标位置的字符
	}
	return s;  //返回这些映射的字符
}
